package com.xlhj.yucloud.config;

import com.xlhj.yucloud.filter.JwtAuthenticationTokenFilter;
import com.xlhj.yucloud.handler.JwtAccessDeniedHandler;
import com.xlhj.yucloud.handler.JwtAuthenticationEntryPoint;
import com.xlhj.yucloud.handler.JwtAuthenticationFailureHandler;
import com.xlhj.yucloud.handler.JwtAuthenticationSuccessHandler;
import com.xlhj.yucloud.handler.JwtLogoutSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @author: liucaijing
 * @description: SecurityConfig
 * @date: 2021/9/10 9:56
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint authenticationEntryPoint;
    @Autowired
    private JwtAccessDeniedHandler accessDeniedHandler;
    @Autowired
    private JwtAuthenticationFailureHandler authenticationFailureHandler;
    @Autowired
    private JwtAuthenticationSuccessHandler authenticationSuccessHandler;
    @Autowired
    private JwtLogoutSuccessHandler logoutSuccessHandler;
    @Autowired
    private JwtAuthenticationTokenFilter authenticationTokenFilter;
    @Autowired
    @Qualifier(value = "userDetailsServiceImpl")
    private UserDetailsService userDetailsService;
    private static final String[] WHITELIST_URL = {"/user/login", "/captchaImage"};
    private static final String[] WHITELIST_SOURCE = {"/**/*.css", "/webjars/**"};

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()
                //CSRF禁用,不使用session
                .csrf().disable()
                //登录配置
                //.formLogin().loginPage("/login").loginProcessingUrl("/login")
                //.successHandler(authenticationSuccessHandler)
                //.failureHandler(authenticationFailureHandler)
                //退出配置
                //.and()
                .logout()
                .logoutSuccessHandler(logoutSuccessHandler)
                //配置异常处理
                .and()
                .exceptionHandling()
                .authenticationEntryPoint(authenticationEntryPoint)
                .accessDeniedHandler(accessDeniedHandler)
                //设置白名单
                .and()
                .authorizeRequests()
                .antMatchers(WHITELIST_URL).anonymous()
                .antMatchers(HttpMethod.GET, WHITELIST_SOURCE).permitAll()
                .anyRequest().authenticated()
                //禁用session
                .and()
                .sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                //禁用网页嵌入iframe
                .and()
                .headers().frameOptions().disable()
                //配置自定义过滤器
                .and()
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 解决无法直接注入AuthenticationManager
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}
